package com.tanhua.backstage.service;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanhua.backstage.vo.PageResult;
import com.tanhua.backstage.vo.UserVo;
import com.tanhua.common.mapper.UserInfoMapper;
import com.tanhua.common.mapper.UserMapper;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.dubbo.server.api.ManageFreezeApi;
import com.tanhua.dubbo.server.api.UserLikeApi;
import com.tanhua.dubbo.server.api.UserLocationApi;
import com.tanhua.dubbo.server.enums.FreezingRangeEnum;
import com.tanhua.dubbo.server.vo.UserLocationVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @PackageName: com.tanhua.backstage.service
 * @Classname: UsersService
 * @Author: zlqjava@163.com
 * @Date: 2021/10/13 21:49
 */
@Service
@Slf4j
public class UsersService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private UserMapper userMapper;

    @Reference(version = "1.0.0")
    private ManageFreezeApi manageFreezeApi;

    @Reference(version = "1.0.0")
    private UserLocationApi userLocationApi;

    @Reference(version = "1.0.0")
    private UserLikeApi userLikeApi;

    //查询用户基本资料，数据分页;
    public PageResult queryUserByPage(Integer page, Integer pageSize, Long id, String nickname, String city) {
        //创建分页对象;
        PageResult pageResult = new PageResult();

        //设置模糊查询条件;
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(null != id, "user_id", id);                           //根据id;
        queryWrapper.like(StringUtils.isNotBlank(nickname), "nick_name", nickname);     //根据昵称;
        queryWrapper.like(StringUtils.isNotBlank(city), "city", city.replace("省", ""));                  //根据城市;

        //查询总记录数;
        Integer count = this.userInfoMapper.selectCount(queryWrapper);

        //根据查询条件，分页查询用户数据;

        IPage<UserInfo> userPages = new Page(page, pageSize);
        userPages = this.userInfoMapper.selectPage(userPages, queryWrapper);
        //将查询到的用户数据存入集合中;
        List<UserVo> userInfoList = new ArrayList<>();

        for (UserInfo userInfo : userPages.getRecords()) {
            //填充数据;
            UserVo userVo = new UserVo();

            userVo.setId(userInfo.getId());                 //用户id;
            userVo.setNickname(userInfo.getNickName());     //昵称;
            userVo.setSex(userInfo.getSex().toString());    //性别;
            userVo.setCity(userInfo.getCity());             //城市;

            //拼接字符串，将用户冻结状态，获取字符串，去判断，isAccountState的状态
            Boolean result1 = manageFreezeApi.isAccountState(Convert.toInt(userInfo.getUserId()), FreezingRangeEnum.MAKE);
            Boolean result2 = manageFreezeApi.isAccountState(Convert.toInt(userInfo.getUserId()), FreezingRangeEnum.DYNAMIC);
            Boolean result3 = manageFreezeApi.isAccountState(Convert.toInt(userInfo.getUserId()), FreezingRangeEnum.REGISTER);
            Boolean result = result1 || result2 || result3;
            userVo.setUserStatus(result ? "2" : "1");      //用户状态
            if (ObjectUtil.isEmpty(userLocationApi.queryByUserId(userInfo.getUserId()))) {
                userVo.setLastActiveTime(Convert.toLong(DateUtil.timeToSecond("1970:1:1")));//最后登录时间
            } else {
                userVo.setLastActiveTime(userLocationApi.queryByUserId(userInfo.getUserId()).getLastUpdated());//最后登录时间
            }


            //将每一条用户数据存入集合中;
            userInfoList.add(userVo);
        }

        //封装结果集;
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        pageResult.setCounts(count);
        pageResult.setItems(userInfoList);
        //返回结果集;
        return pageResult;
    }


    //查询用户详细数据;
    public UserVo queryUserById(Long userId) {
        //创建对象存储用户数据;
        UserVo userVo = new UserVo();
        //根据用户id查询详细数据;
        UserInfo userInfo = this.userInfoMapper.selectById(userId);
        //判断查询结果是否为空;
        if (null == userInfo) {
            //没有查询到返回null;
            return null;
        }

        //查询出结果后，填充数据;
        userVo.setId(userInfo.getUserId());                         //用户id;
        userVo.setNickname(userInfo.getNickName());                 //昵称;
        userVo.setSex(StringUtils.equals(userInfo.getSex().toString(), "1") ? "男" : "女");   //性别;
        userVo.setAge(userInfo.getAge());                           //年龄;
        userVo.setIncome(Long.valueOf(userInfo.getIncome()));       //收入;
        userVo.setCreated(userInfo.getCreated().getTime());         //创建时间;
        userVo.setCity(userInfo.getCity());                         //创建城市;
        userVo.setLogo(userInfo.getLogo());                         //头像;
        userVo.setTags(userInfo.getTags());                         //标签;
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("id", userId);
        User user = userMapper.selectOne(wrapper);
        userVo.setMobile(user.getMobile());

        userVo.setCountBeLiked(this.userLikeApi.queryFanCount(userId));         //粉丝数;
        userVo.setCountLiked(this.userLikeApi.queryLikeCount(userId));          //喜欢数;
        userVo.setCountMatching(this.userLikeApi.queryMutualLikeCount(userId));   //互相喜欢数;

        userVo.setPersonalSignature("这个人很懒，什么也没有留下。。。");    //个性签名;
        userVo.setOccupation(userInfo.getIndustry());                                 //职业;

        //判断用户的冻结状态，并封装
        Boolean result1 = manageFreezeApi.isAccountState(Convert.toInt(userInfo.getUserId()), FreezingRangeEnum.MAKE);
        Boolean result2 = manageFreezeApi.isAccountState(Convert.toInt(userInfo.getUserId()), FreezingRangeEnum.DYNAMIC);
        Boolean result3 = manageFreezeApi.isAccountState(Convert.toInt(userInfo.getUserId()), FreezingRangeEnum.REGISTER);
        Boolean result = result1 || result2 || result3;
        userVo.setUserStatus(result ? "2" : "1");      //用户状态

        UserLocationVo userLocationVo = userLocationApi.queryByUserId(userId);//最后登陆地点;
        Long updated = userLocationVo.getUpdated();
        String address = userLocationVo.getAddress();
        userVo.setLastActiveTime(updated);//最后登录时间
        userVo.setLastLoginLocation(address);

        //返回对象;
        return userVo;
    }
}
